﻿using System.Collections.Generic;
using System.Linq;
using DTD.Repositories.Entities;
using DTD.Repositories.Interfaces;

namespace DTD.Repositories
{
    public class TaskRepository: RepositoryBase, ITaskRepository
    {
        private ICategoryRepository categoryRepository = new CategoryRepository();

        public List<Task> GetTasksByCategory(int categoryId)
        {
            return dataContext.Tasks.Where(t => t.CategoryId == categoryId).OrderBy(p => p.Status).ToList();
        }

        public void Add(Task task)
        {
            // TODO: Hard coded default user and category
            task.User = dataContext.Users.Where(u => u.Id == Constants.DefaultUserId).SingleOrDefault();
            task.CategoryId = 1;
            dataContext.Tasks.InsertOnSubmit(task);
            dataContext.SubmitChanges();
        }

        public void Update(Task task, string category)
        {
            var ta = dataContext.Tasks.Where(t => t.Id == task.Id).SingleOrDefault();
            ta.Title = task.Title;
            ta.Description = task.Description;

            if (!string.IsNullOrWhiteSpace(category))
            {
                Category cat = dataContext.Categories.Where(c => c.Title == category).SingleOrDefault();
            
                if (cat == null)
                {
                    cat = new Category {Title = category};
                    categoryRepository.Add(cat);
                }
                ta.CategoryId = cat.Id;
            }

            dataContext.SubmitChanges();
        }

        public void MarkAsDone(int Id)
        {
            var task = dataContext.Tasks.Where(t => t.Id == Id).SingleOrDefault();
            if(task != null)
            {
                task.Status = (int) TaskStatuses.Ready;
            }
            dataContext.SubmitChanges();
        }

        public List<Task> GetAll()
        {
            return dataContext.Tasks.ToList();
        }
    }
}